<?php

declare (strict_types=1);

namespace App\Common\Modular\Administer\Model;

use Core\Basics\BasicsModel;
use Hyperf\Database\Model\Events\Deleted;
use Hyperf\Database\Model\Events\Saved;
use Hyperf\Database\Model\Relations\HasOne;
use Psr\SimpleCache\InvalidArgumentException;
use Zms\HyperfCasts\ArrjoinCasts;
use Zms\HyperfCasts\StrtotimeCasts;
use Core\HyperfUnit\Callback;
/**
 * @property int $id
 * @property int $pid 上级菜单
 * @property string $name 部门名称
 * @property int $sort 排序
 * @property int $level 层级
 * @property string $manage_id 管理员
 * @property array $relevance 层级
 * @property string $remark 备注信息
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 *
 *
 * @property UserModel $manage 部门主管
 */
class DepartmentModel extends BasicsModel
{
    /**
     * The table associated with the model.
     *
     * @var null|string
     */
    protected ?string $table = 'administer_department';


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected array $fillable = [];


    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected array $casts = [
        'id' => 'int',
        'pid' => 'integer',
        'sort' => 'integer',
        'level' => 'integer',
        'manage_id' => 'integer',
        'relevance' => ArrjoinCasts::class,
        'created_at' => StrtotimeCasts::class,
        'updated_at' => StrtotimeCasts::class
    ];

    /**
     * 数据变动事件触发清空缓存
     * @param Saved $event
     * @return void
     * @throws InvalidArgumentException
     */
    public function saved(Saved $event): void
    {
        Callback::ClearGroup(UserModel::class);
    }


    /**
     * 数据删除时触发清空缓存
     * @param Deleted $event
     * @return void
     * @throws InvalidArgumentException
     */
    public function deleted(Deleted $event): void
    {
        Callback::ClearGroup(UserModel::class);
    }


    /**
     * 关联负责人
     * @return HasOne
     */
    public function manage(): HasOne
    {
        return $this->hasOne(UserModel::class, 'id', 'manage_id');
    }
}

